import Vue from 'vue'

import { auth, getPermissions } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

import {
  AVATAR,
  NAME
} from '@/store/mutation-types'

const state = {
  accessToken: '',
  refreshToken: '',
  name: '',
  avatar: '',
  permissions: [],
  actions: []
}

const mutations = {
  SET_TOKEN: (state, accessToken) => {
    state.accessToken = accessToken
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_NICKNAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_ACTIONS: (state, actions) => {
    state.actions = actions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      auth({ grantType: 'password', account: username.trim(), password: password }).then(response => {
        const { data } = response

        const { accessToken, refreshToken, nickName, avatar } = data

        commit('SET_TOKEN', accessToken)
        commit('SET_REFRESH_TOKEN', refreshToken)
        commit('SET_NICKNAME', nickName)
        commit('SET_AVATAR', avatar)

        // 保存信息到缓存中
        setToken(data.accessToken, data.refreshToken, data.accessTokenExpire)
        Vue.ls.set(AVATAR, avatar)
        Vue.ls.set(NAME, nickName)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user login
  refreshToken({ commit }) {
    return new Promise((resolve, reject) => {
      auth({ grantType: 'refresh_token', refreshToken: getToken(true) }).then(response => {
        const { data } = response

        const { accessToken, refreshToken, nickName, avatar } = data

        commit('SET_TOKEN', accessToken)
        commit('SET_REFRESH_TOKEN', refreshToken)
        commit('SET_NICKNAME', nickName)
        commit('SET_AVATAR', avatar)

        // 保存信息到缓存中
        setToken(data.accessToken, data.refreshToken, data.accessTokenExpire)
        Vue.ls.set(AVATAR, avatar)
        Vue.ls.set(NAME, nickName)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user permissions
  getPermissions({ commit, state }) {
    return new Promise((resolve, reject) => {
      getPermissions(state.token).then(response => {
        const { data } = response

        console.log(':ssfds:L' + data)

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const permissions = data

        // permissions must be a non-empty array
        if (!permissions || permissions.length <= 0) {
          reject('getPermissions: permissions must be a non-null array!')
        }

        const newPermissions = []
        const newActions = []

        if (permissions.menu.length != null) {
          permissions.menu.map(item => {
            newPermissions.push(item.permission)
          })
        }
        if (permissions.permission.length != null) {
          permissions.permission.map(item => {
            newActions.push(item.path)
          })
        }

        commit('SET_PERMISSIONS', newPermissions)
        commit('SET_ACTIONS', newActions)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_PERMISSIONS', [])
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

